from __future__ import annotations

import os
from dotenv import load_dotenv

from src.utils.logger import setup_logging
from src.utils.path_utils import ensure_directories_from_config
import argparse
from src.processors.excel_processor import export_excel_to_csv_and_txt
from src.utils.config_loader import load_config


def main() -> None:
    # Load environment variables from .env
    load_dotenv()

    # Optional: propagate env overrides (e.g., LOG LEVEL) later if needed
    setup_logging("config/config.yaml")

    # Ensure required directories exist based on config
    ensure_directories_from_config("config/config.yaml")

    # Entry banner via logging (avoid print per project rules)
    import logging
    logging.getLogger(__name__).info("DYVA started. Environment: %s", os.getenv("DYVA_ENV", "dev"))

    # CLI args: --max-rows, --sheet-name
    parser = argparse.ArgumentParser(description="DYVA Excel→CSV/TXT 批量导出")
    parser.add_argument("--max-rows", type=int, default=None, help="仅处理前N行，用于抽样或集成测试")
    parser.add_argument("--sheet-name", type=str, default=None, help="指定Excel工作表名；默认读取第一个工作表")
    args = parser.parse_args()

    # Load config for input_excel path
    cfg = load_config("config/config.yaml")
    excel_path = cfg.get("paths", {}).get("input_excel", "data/研究样本表.xlsx")

    # Run export pipeline
    metas, errors, error_summary, csv_path, txt_paths = export_excel_to_csv_and_txt(
        excel_path,
        config_path="config/config.yaml",
        sheet_name=args.sheet_name,
        max_rows=args.max_rows,
    )

    logging.getLogger(__name__).info(
        "Export finished: metas=%d, errors=%d, csv=%s, txt_files=%d, error_summary=%s",
        len(metas), len(errors), str(csv_path), len(txt_paths), error_summary,
    )


if __name__ == "__main__":
    main()


